package com.chenglu.android.mine.setting;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NavigationRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.chenglu.android.R;
import com.chenglu.android.bean.SmsCodeBean;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.GlideEngine;
import com.chenglu.android.common.utils.GlideUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.widget.RadiusImageView;
import com.chenglu.android.mine.bean.PutFileBean;
import com.chenglu.android.mine.bean.UserInfoBean;
import com.chenglu.android.mine.setting.mvp.contract.SettingContract;
import com.chenglu.android.mine.setting.mvp.presenter.SettingPresenter;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023 6 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：
 */
public class SettingActivity extends BaseFullScreenActivity<SettingPresenter> implements SettingContract.View {


    @BindView(R.id.ic_back)
    ImageView icBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ll_uset_photo)
    LinearLayout llUsetPhoto;
    @BindView(R.id.rl_nickname)
    RelativeLayout rlNickname;
    @BindView(R.id.iv_photo)
    RadiusImageView ivPhoto;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_register_time)
    TextView tvRegisterTime;

    String aaccessToken;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ButterKnife.bind(this);
        mPresenter = new SettingPresenter();
        mPresenter.attachView(this);

        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);
        tvTitle.setText("我的");

        aaccessToken = getToken();

        mPresenter.getUserInfo(aaccessToken);
        initdata();

    }

    private void initdata() {

    }



    //更新用户信息
    private void toUserUpdate(String avatar, String text) {

        JSONObject json = new JSONObject();
        try {
            json.put("avatar", avatar);
            json.put("id", dataBean.getId());
            json.put("nickName", text);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mPresenter.getUserUpdate(aaccessToken, mPresenter.getRequestBody(json));
    }

    private void requestPermission() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                // 申请多个权限
//                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                // 设置权限请求拦截器（局部设置）
                //.interceptor(new PermissionInterceptor())
                // 设置不触发错误检测机制（局部设置）
//                .unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        SPUtils.setBoolean(Constant.ISWRITESTORAGE, false);
                        //弹图片
                        showPicture();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        SPUtils.setBoolean(Constant.ISWRITESTORAGE, false);
                    }
                });

    }

    private void showPicture() {
        new XPopup.Builder(SettingActivity.this)
                .asBottomList("", new String[]{"从相册中选取", "拍照",},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                switch (position) {
                                    case 0:
                                        showOpenGallery();
                                        break;
                                    case 1:
                                        showOpenCamera();
                                        break;
                                }
                            }
                        })
                .show();
    }

    @OnClick({R.id.ll_uset_photo, R.id.rl_nickname,R.id.ic_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_uset_photo:
                boolean isStorage = SPUtils.getBoolean(Constant.ISWRITESTORAGE, true);
                if (isStorage) {
                    requestPermission();
                } else {
                    if (XXPermissions.isGranted(mContext, Permission.READ_EXTERNAL_STORAGE
                            , Permission.WRITE_EXTERNAL_STORAGE)) {
                        showPicture();
                    } else {
                        ToastUtils.show("请去权限管理允许该权限！");
                    }

                }
                break;
            case R.id.rl_nickname:

                new XPopup.Builder(this).asInputConfirm("修改昵称", "", tvNickname.getText().toString(), "请输入昵称",
                        new OnInputConfirmListener() {
                            @Override
                            public void onConfirm(String text) {
                                if (!text.isEmpty() && !text.equals(tvNickname.getText().toString())) {
                                    toUserUpdate(dataBean.getAvatar(), text);

                                }
                            }
                        })
                        .show();
                break;
            case R.id.ic_back:
                finish();
                break;
        }


    }

    //打开相册
    private void showOpenGallery() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .isCompress(true)
                .isAndroidQTransform(true) //Android Q版本下是否需要拷贝文件至应用沙盒内
                .minimumCompressSize(100) // 小于多少kb的图片不压缩
                .compressQuality(50) //图片压缩后输出质量
                .maxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            mPresenter.getPutFile(aaccessToken, new File(result.get(0).getAndroidQToPath()));
                        } else {
                            mPresenter.getPutFile(aaccessToken, new File(result.get(0).getCompressPath()));
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }


    //打开摄像头
    private void showOpenCamera() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .isCompress(true)
                .isAndroidQTransform(true) //Android Q版本下是否需要拷贝文件至应用沙盒内
                .minimumCompressSize(100) // 小于多少kb的图片不压缩
                .compressQuality(50) //图片压缩后输出质量
                .maxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            mPresenter.getPutFile(aaccessToken, new File(result.get(0).getAndroidQToPath()));
                        } else {
                            mPresenter.getPutFile(aaccessToken, new File(result.get(0).getCompressPath()));
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }


    private UserInfoBean.Data dataBean;

    @Override
    public void getUserInfo(UserInfoBean bean) {
        if(bean.getCode().equals(Constant.HTTPCODE200)){
            dataBean = bean.getData();
            GlideUtils.setImageView(mContext,bean.getData().getAvatar(),ivPhoto,15);
//            Glide.with(mContext).load(bean.getData().getAvatar()).into(ivPhoto);
            tvNickname.setText(bean.getData().getNickName());
            tvPhone.setText(bean.getData().getMobile());
            tvRegisterTime.setText(bean.getData().getCreateTime()+ "");
        }else {
            ToastUtils.show(bean.getMsg());
        }


    }


    @Override
    public void getUserUpdate(SmsCodeBean bean) {

        mPresenter.getUserInfo(aaccessToken);
    }


    @Override
    public void getPutFile(PutFileBean bean) {
        toUserUpdate(bean.getData().getLink(), dataBean.getNickName());
    }


    @Override
    public void onError(String errorMsg) {
        super.onError(errorMsg);
        ToastUtils.show("测试异常");
    }
}
